package com.leyou.common.advice;

import com.leyou.common.exception.LyException;
import com.leyou.common.vo.ExceptionResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.stream.Collectors;

@ControllerAdvice
public class CommonExceptionHandler {

    @ExceptionHandler(LyException.class)
    public ResponseEntity<ExceptionResult> handleException(LyException e) {
        return ResponseEntity
                .status(e.getExceptionEnum().getStatus())
                .body(new ExceptionResult(e.getExceptionEnum()));
    }

    @ExceptionHandler(BindException.class)
    public ResponseEntity<ExceptionResult> handleException(BindException e) {
        ExceptionResult result = new ExceptionResult();
        result.setStatus(400);
        result.setMessage(e.getBindingResult().getFieldErrors()
                .stream().map(f -> f.getDefaultMessage()).collect(Collectors.joining("|")));

        return ResponseEntity
                .status(HttpStatus.BAD_REQUEST)
                .body(result);
    }
}
